//
//  AuthViewController.swift
//  新浪微博项目
//
//  Created by 王炯 on 16/7/20.
//  Copyright © 2016年 王炯. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking


class AuthViewController: UIViewController
{

    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        //布局界面
        self.setUpUI()
    }
    
    //界面消失时将loading直线从主控件移除
    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated)
        
        self.loadingLine.removeLine()
    }
    
    
    //懒加载webView
   private lazy var webView:UIWebView = UIWebView()
    
    //懒加载一条loading直线
    private lazy var loadingLine:LoadingView = LoadingView()
    
    
    //主界面为webView
    override func loadView()
    {
        
        //(1)根据appkey和appSecret拼接相关的请求信息
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDIRECT_URI)"
        
        //(2)string-->urlString
        let url = NSURL(string:urlString)
        
        //判断url
        guard let u = url else
        {
            return
        }
        
        //(3)url--->request
        let request = NSURLRequest(URL: u)
        
        //(4)加载request
        webView.loadRequest(request)
        
        
        
        webView.delegate = self
        
        self.view = webView
    }
    

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
    }
    
    //布局界面
    func setUpUI()
    {
        self.view.backgroundColor = UIColor.whiteColor()
       
        //设置navigationController
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageStr: nil, target: self, action: #selector(AuthViewController.cancelClick))
        
        self.navigationItem.rightBarButtonItem = NewBarButtonItem(title: "自动填充", imageStr: nil, target: self, action:#selector(AuthViewController.autoFillClick))
        
        self.title = "微博登录"
        
        
        //将Loading进度条插入到navigationController上
        self.navigationController?.view.insertSubview(self.loadingLine, belowSubview: navigationController!.navigationBar)
    }
    
    
    deinit
    {
        print("VC销毁了")
    }
    
    //取消按钮
    @objc private func cancelClick()
    {
        //界面消失
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充按钮
    @objc private func autoFillClick()
    {
        //自动填充，自动填入你的微博用户名和密码
        let jsString = "document.getElementById('userId').value='\(weiboName)',document.getElementById('passwd').value='\(weiboPassWord)'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
}


//在扩展中实现webView的代理方法
//让扩展遵守协议
extension AuthViewController:UIWebViewDelegate
{
    //(1)web开始加载
    func webViewDidStartLoad(webView: UIWebView)
    {
        //遮罩开启
        //SVProgressHUD.show()
        self.loadingLine.startLoading()
    }
    
    //(2)web结束加载
    func webViewDidFinishLoad(webView: UIWebView)
    {
        //遮罩消失
        //SVProgressHUD.dismiss()
        self.loadingLine.endLoading()
    }
    
    //(3)web加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?)
    {
        
    }
    
    //(4)监听webView 将要加载的request 
    /*
     返回的值:
     true:继续加载
     false:停止加载
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        //监听webView将要加载的request
        let urlString = request.URL?.absoluteString
        
        //逐步获取code
        guard let u = urlString else
        {
            return false
        }
        
        if u.hasPrefix(APPREDIRECT_URI)
        {
            
            //获取urlString中“?”后面的所有信息
            let urlCode = request.URL?.query
            guard var code = urlCode else
            {
                return false
            }
            code = code.substringFromIndex("code=".endIndex)
            
            //根据最终的code来请求accessToken授权
            //GetAccessToken(code)
            
            //利用ViewModel工具单例类来请求accessToken授权
            AuthViewModel.AuthViewModelTools.GetAccessToken(code, isSuccess: { (isSucc) in
                
                print(isSucc)
                
                //当网络信息获取失败时
                if !isSucc
                {
                    print("请求工具获取网络信息失败")
                    
                    return
                }
                
                print("我已经成功从网络获取到了数据了")
                print("登录情况是:\(AuthViewModel.AuthViewModelTools.isLogin)")
                
                //拿到数据之后,关闭当前的界面,并返回到响应的界面
                //用false表示不会在跳转到主界面了
                self.dismissViewControllerAnimated(false, completion: {
                    
                    //当用户登录成功时
                    //先跳转到欢迎用户界面
                    UIApplication.sharedApplication().keyWindow?.rootViewController = WelocomeController()
                    
                    
                })
                
            })
            
            //停止加载回调页
            return false
        
        }
        
        return true
    }

}
